//
//  PracticeController.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/7/29.
//

import UIKit
import ETKeyboard
import SVProgressHUD
import iosMath
import AVKit

private let kDecimal2FractionSymbol: String = "—"

class PracticeController: BaseViewController {
    
    /// 当前下标
    var currentIndex = 0
    var topics = [BaseTopic]()
    var type: PracticeType = .twoDigitSubtraction
    
    // 计时
    private var seconds: Int = 0
    
    @IBOutlet weak var topicLabel: MTMathUILabel!
    @IBOutlet weak var answerTextField: UITextField!
    @IBOutlet weak var latexLabel: MTMathUILabel!
    @IBOutlet weak var quantityTips: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        topics = getDatas()
        setTopic()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        setupTimer(count: 1)
    }
    
    private func setupUI() {
        title = "00:00"
        topicLabel.textColor = .label
        topicLabel.fontSize = kTopicFontSize
        topicLabel.textAlignment = .center
        latexLabel.textColor = .label
        latexLabel.fontSize = kTopicFontSize
        latexLabel.textAlignment = .center
        quantityTips.textColor = .systemGray2
        
        answerTextField.clean()
        answerTextField.font = kTopicFont
        answerTextField.becomeFirstResponder()
        answerTextField.inputAccessoryView = generateKeyboardToolView()
        
        let keyboard = ETKeyboardView(type: .customNumber1)
        keyboard.systemSoundId = 1103
        answerTextField.inputView = keyboard
        keyboard.returnKeyBlock = {
            self.next()
        }
        keyboard.specialKeyBlock = { [weak self] type in
            if type == .clear {
                self?.latexLabel.latex = ""
            }
        }
        
        setupTimer(count: 1)

        NotificationCenter.default.addObserver(self, selector: #selector(restart(notifi:)), name: .restart, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(textFieldChange), name: UITextField.textDidChangeNotification, object: nil)
        
        answerTextField.isHidden = true
    }
    
    @objc private func textFieldChange() {
        let text = answerTextField.text ?? "1"
        latexLabel.latex = text
        
        if type == .decimal2Fraction {
            if text.contains(kDecimal2FractionSymbol) {
                let arr = text.components(separatedBy: kDecimal2FractionSymbol)
                latexLabel.latex = "\\frac{\(arr[1])}{\(arr[0])}"
            }
        }
    }
    
    @objc private func restart(notifi: Notification?) {
        if let dict = notifi?.userInfo {
            let flag = dict[kNotiKey_IsNext] as! Bool
            if flag {
                type = type.getNext()
                SVProgressHUD.showInfo(withStatus: type.rawValue)
            }
        }
        
        restart2()
    }
    
    @objc private func restart2() {
        title = "00:00"
        seconds = -1
        currentIndex = 0
        clearInputData()
        topics = getDatas()
        showQuantityTips()

        setupTimer(count: 1)
        startTimer()
        setTopic()
    }
    
    private func clearInputData() {
        answerTextField.text = ""
        latexLabel.latex = ""
    }
    
    private func next() {
        let topic = topics[currentIndex]
        let answerText = answerTextField.text
        
        showQuantityTips()
        
        // 统计数量
        if !(answerText?.isEmpty ?? true) {
            let key = Field.calc.doneTotalNumber.rawValue
            var num = (Int)(KeyValueStore.get(key) ?? "0") ?? 0
            num = num + 1
            KeyValueStore.set(key: key, value: "\(num)")
        }
        
        if type == .decimal2Fraction {
            let text = answerText ?? "1"
            if text.contains(kDecimal2FractionSymbol) {
                let arr = text.components(separatedBy: kDecimal2FractionSymbol)
                let denominator = Float(arr[0]) ?? 1
                let numerator = Float(arr[1]) ?? 0.0
                topic.setInputAnswer(answer: nil, numerator: numerator, denominator: denominator)
            }
        } else if type == .base {
            let text = answerText ?? "1"
            let denominator = Float(text) ?? 0.0
            topic.setInputAnswer(answer: nil, numerator: 0.0, denominator: denominator)
        } else {
            topic.setInputAnswer(answer: answerText)
        }
        
        clearInputData()
        
        if topic.answerIsCorrect() {
            SVProgressHUD.showSuccess(withStatus: "对")
        } else {
            SVProgressHUD.showError(withStatus: "错")
        }
        
        // 结束计算，跳转结果页
        if currentIndex == topics.count - 1 {
            jumpPage()
            return
        }
        
        currentIndex = currentIndex + 1
        setTopic()
    }
    
    private func jumpPage() {
        pauseTimer()
        
        let r = ResultViewController()
        r.data = topics.map { $0.getResultDesc() }
        navigationController?.pushViewController(r, animated: true)
        
        TimeStatisticsStore.record(uuid: uuid, duration: TimeInterval(seconds), type: .calculate)
    }
    
    private func setTopic() {
        let topic = topics[currentIndex]
        topicLabel.latex = topic.getTopicDesc()
        showQuantityTips()
    }
    
    override func timing() {
        super.timing()
        
        seconds = seconds + 1
        title = seconds.toSecondStr()
    }
    
    private func getDatas() -> [BaseTopic] {
        return GenerateTopic().generateDatas(type: type)
    }
    
    /// 显示题目总数和当前题目数
    private func showQuantityTips() {
        quantityTips.text = "\(currentIndex + 1)/\(topics.count)"
    }
    
    private func generateKeyboardToolView() -> UIView {
        let width = UIScreen.main.bounds.width
        let btnWidth: CGFloat = 95
        let btnHeight: CGFloat = 46
        let btnY: CGFloat = 4
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 50))
        view.backgroundColor = UIColor(named: "keyboard_bg")
        
        let leftRightMargin: CGFloat = 40
        let btn = BaseButton(frame: CGRect(x: leftRightMargin, y: btnY, width: btnWidth, height: btnHeight))
        btn.setTitle("重来", for: .normal)
        btn.setTitleColor(.label, for: .normal)
        btn.normalColor = UIColor(named: "keyboard_btn_bg")
        btn.addTarget(self, action: #selector(restart2), for: .touchUpInside)
        btn.setFillet()
        
        view.addSubview(btn)
        
        return view
    }
    
    @objc private func addSymbol() {
        let text = answerTextField.text
        answerTextField.text = (text ?? "") + kDecimal2FractionSymbol
        latexLabel.latex = (text ?? "") + kDecimal2FractionSymbol
        textFieldChange()
    }
}

